<template>
  <div class="follow-up-plan">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <div>
        <el-select
          v-model="selectedDoctor"
          style="width: 160px; margin-right: 16px"
          :placeholder="t('followUpPlan.search.selectDoctor')"
          class="search-item"
        >
          <el-option
            v-for="item in doctorList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
        <el-select
          v-model="planType"
          style="width: 160px; margin-right: 16px"
          :placeholder="t('followUpPlan.search.planCategory')"
          class="search-item"
        >
          <el-option
            v-for="item in followUpPlanConditionList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-input
          v-model="searchUser"
          style="width: 200px; margin-right: 16px"
          :placeholder="t('followUpPlan.search.searchUser')"
          class="search-item"
        />
        <el-button @click="resetSearch">{{
          t("followUpPlan.search.reset")
        }}</el-button>
        <el-button type="primary" @click="searchTasks">{{
          t("followUpPlan.search.search")
        }}</el-button>
      </div>
      <!-- 创建任务按钮 -->
      <el-button type="primary" class="create-task-btn" @click="createTask">
        {{ t("followUpPlan.buttons.createTaskPlan") }}
      </el-button>
    </div>

    <div class="main-content">
      <!-- 日历部分 -->
      <div v-loading="loading" class="calendar-container">
        <el-calendar v-model="date" :first-day-of-week="1">
          <template #header="{}">
            <div class="calendar-header">
              <div class="calendar-header-left">
                <!-- 年月 -->
                <span class="year-month">{{ currentDate }}</span>

                <!-- 统计信息 -->
                <div class="statistics">
                  <span
                    >{{ t("followUpPlan.statistics.monthlyCompleted") }}：{{
                      finishedCount
                    }}{{ t("followUpPlan.statistics.times") }}</span
                  >
                  <span class="divider">|</span>
                  <span
                    >{{ t("followUpPlan.statistics.pending") }}：{{
                      unfinishedCount
                    }}{{ t("followUpPlan.statistics.times") }}</span
                  >
                  <span class="divider">|</span>
                  <span
                    >{{ t("followUpPlan.statistics.canceled") }}：{{
                      canceledCount
                    }}{{ t("followUpPlan.statistics.times") }}</span
                  >
                </div>
              </div>

              <div class="calendar-header-right">
                <!-- 导航按钮 -->
                <div class="nav-buttons">
                  <el-button text @click="navigatePrevious">
                    <el-icon><ArrowLeft /></el-icon>
                  </el-button>
                  <el-button
                    text
                    style="margin-left: 0px"
                    @click="navigateNext"
                  >
                    <el-icon><ArrowRight /></el-icon>
                  </el-button>
                  <el-button text style="margin-left: 0px" @click="goToday">{{
                    t("followUpPlan.buttons.today")
                  }}</el-button>
                </div>

                <!-- 视图切换 -->
                <el-radio-group v-model="calendarView" size="small">
                  <el-radio-button
                    :label="t('followUpPlan.calendar.views.day')"
                    >{{ t("followUpPlan.calendar.views.day") }}</el-radio-button
                  >
                  <el-radio-button
                    :label="t('followUpPlan.calendar.views.week')"
                    >{{
                      t("followUpPlan.calendar.views.week")
                    }}</el-radio-button
                  >
                  <el-radio-button
                    :label="t('followUpPlan.calendar.views.month')"
                    >{{
                      t("followUpPlan.calendar.views.month")
                    }}</el-radio-button
                  >
                </el-radio-group>
              </div>
            </div>
          </template>
          <template #date-cell="{ data }">
            <div
              :class="[
                'calendar-cell',
                { 'is-current-week': isInCurrentWeek(data.day) }
              ]"
            >
              <div class="date-content">
                <span class="date-number">{{
                  data.day.split("-").slice(-1)[0]
                }}</span>
              </div>
              <div v-if="hasTasksOnDate(data)" class="task-indicators">
                <span
                  v-for="task in getTasksForDate(data).slice(0, 2)"
                  :key="task.taskId"
                  :class="['task-dot', `task-type-1`]"
                >
                  {{ task.userName || "未知" }}
                </span>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>

      <!-- 右侧任务详情卡片 -->
      <div class="task-details">
        <div v-if="!selectedTasks.length" class="empty-state">
          <el-empty :description="t('followUpPlan.calendar.empty')" />
        </div>
        <div v-else class="task-list">
          <div
            v-for="task in selectedTasks"
            :key="task.taskId"
            class="task-card"
          >
            <!-- 时间标题 -->
            <div class="task-time">
              {{ formatDateTime(task.startDate, task.endDate) }}
            </div>

            <!-- 人员信息 -->
            <div class="task-people">
              <!-- 医生信息 -->
              <div class="person-info">
                <div class="avatar-wrapper">
                  <el-avatar :size="48" :src="task.followUpUserAvatar" />
                  <div v-if="task.gender == 1" class="gender-icon">
                    <el-icon color="#FF69B4"><Female /></el-icon>
                  </div>
                  <div v-if="task.gender == 2" class="gender-icon">
                    <el-icon color="#409EFF"><Male /></el-icon>
                  </div>
                </div>
                <div class="info-text">
                  <div class="name">{{ task.followUpUserName }}</div>
                  <div class="doctor">{{ task.followUpUserRole }}</div>
                </div>
              </div>

              <!-- 患者信息 -->
              <div class="person-info">
                <div class="avatar-wrapper">
                  <el-avatar :size="48" :src="task.userAvatar" />
                  <div v-if="task.gender == 1" class="gender-icon">
                    <el-icon color="#FF69B4"><Female /></el-icon>
                  </div>
                  <div v-if="task.gender == 2" class="gender-icon">
                    <el-icon color="#409EFF"><Male /></el-icon>
                  </div>
                </div>
                <div class="info-text">
                  <div class="name">{{ task.userName || "未知" }}</div>
                  <div class="role">
                    {{
                      task.familyMemberName || t("followUpPlan.roles.executive")
                    }}
                  </div>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="task-actions">
              <a class="action-link primary" @click="editTask(task, 'edit')">{{
                task.taskType === 1
                  ? t("followUpPlan.taskActions.editFollowUp")
                  : task.taskType === 2
                    ? t("followUpPlan.taskActions.editVaccine")
                    : t("followUpPlan.taskActions.editHealthCheck")
              }}</a>
              <a class="action-link primary" @click="editTask(task, 'view')">{{
                task.taskType === 1
                  ? t("followUpPlan.taskActions.viewFollowUp")
                  : task.taskType === 2
                    ? t("followUpPlan.taskActions.viewVaccine")
                    : t("followUpPlan.taskActions.viewHealthCheck")
              }}</a>
              <a
                v-if="task.taskType === 1"
                class="action-link primary"
                @click="fillRecord(task)"
                >{{ t("followUpPlan.taskActions.fillRecord") }}</a
              >
              <a class="action-link danger" @click="cancelTask(task)">{{
                t("followUpPlan.taskActions.cancelFollowUp")
              }}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 任务计划弹窗 -->
    <follow-dialog
      v-model:visible="dialogVisible"
      :mode="dialogMode"
      :task-data="currentTask"
      @submit="handleTaskSubmit"
    />
  </div>
</template>

<script setup>
import { followApi } from "@/api/follow";
import { useToolsStore } from "@/store/modules/tools";
import { ArrowLeft, ArrowRight, Female, Male } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import FollowDialog from "./components/followDialog.vue";
const router = useRouter();

// 国际化
const { t } = useI18n();

// 注册 dayjs 插件
dayjs.extend(isBetween);

// 响应式状态
const selectedDoctor = ref("");
const planType = ref("");
const searchUser = ref("");
const date = ref(new Date());
const calendarView = ref("");
const selectedTasks = ref([]);
const tasks = ref([]);
const finishedCount = ref(0);
const unfinishedCount = ref(0);
const canceledCount = ref(0);
const loading = ref(false);
const doctorList = ref([]);
const dialogVisible = ref(false);
const currentTask = ref(null);
let dialogMode = ref(""); //mode?: 'create' | 'edit' | 'view'; // 组件模式：创建、编辑、查看
const followUpPlanConditionList = computed(() => {
  return toolsStore.getDictData().followUpPlanCondition?.plansTypeList || [];
});
// 监听视图类型变化
watch(calendarView, newView => {
  fetchTasks(date.value);
});

// 计算属性
const currentDate = computed(() => {
  return dayjs(date.value).format("YYYY.MM");
});
const userComId = ref("");
// 方法
// 根据视图类型获取日期范围
const getDateRange = (viewDate, viewType = "month") => {
  const date = dayjs(viewDate);
  const dayText = t("followUpPlan.calendar.views.day");
  const weekText = t("followUpPlan.calendar.views.week");
  const monthText = t("followUpPlan.calendar.views.month");

  switch (viewType) {
    case dayText:
      return {
        startDate: date.startOf("day").valueOf(),
        endDate: date.endOf("day").valueOf()
      };
    case weekText:
      return {
        startDate: date.startOf("week").valueOf(),
        endDate: date.endOf("week").valueOf()
      };
    default: // 月
      return {
        startDate: date.startOf("month").valueOf(),
        endDate: date.endOf("month").valueOf()
      };
  }
};

const fetchTasks = async (targetDate = date.value) => {
  if (loading.value) return;
  loading.value = true;
  try {
    const { startDate, endDate } = getDateRange(targetDate, calendarView.value);

    const response = await followApi.getFollowUpPlanTaskSearchApi({
      taskType: planType.value ? Number(planType.value) : undefined,
      userName: searchUser.value || undefined,
      startDate: Number(startDate),
      endDate: Number(endDate),
      healthManagerId: selectedDoctor.value
        ? Number(selectedDoctor.value)
        : undefined
    });

    // 检查响应数据的结构
    if (response?.data) {
      tasks.value = response.data.taskDetailList || [];
      finishedCount.value = response.data.finishedCount || 0;
      unfinishedCount.value = response.data.unfinishedCount || 0;
      canceledCount.value = response.data.canceledCount || 0;
      selectedTasks.value = tasks.value;
    } else {
      tasks.value = [];
      finishedCount.value = 0;
      unfinishedCount.value = 0;
      canceledCount.value = 0;
      ElMessage.warning(response.message);
    }
  } catch (error) {
    console.error("Error fetching tasks:", error);
    ElMessage.error(t("followUpPlan.messages.fetchTasksFailed"));
    tasks.value = [];
    finishedCount.value = 0;
    unfinishedCount.value = 0;
    canceledCount.value = 0;
  } finally {
    loading.value = false;
  }
};

const hasTasksOnDate = data => {
  if (!data?.day || !tasks.value?.length) return false;

  const dateStr = dayjs(data.day).format("YYYY-MM-DD");

  const hasTasks = tasks.value.some(task => {
    if (!task?.startDate) return false;
    const taskDate = dayjs(Number(task.startDate)).format("YYYY-MM-DD");
    return taskDate === dateStr;
  });

  return hasTasks;
};

const getTasksForDate = data => {
  const dateStr = dayjs(data.day).format("YYYY-MM-DD");
  return tasks.value.filter(task => {
    // 将时间戳转换为日期字符串进行比较
    const taskDate = dayjs(Number(task.startDate)).format("YYYY-MM-DD");
    return taskDate === dateStr;
  });
};

const showTaskDetails = data => {};

// 周几映射函数
const getWeekDay = dayIndex => {
  const weekKeys = [
    "sunday",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday"
  ];
  return t(`followUpPlan.calendar.weekdays.${weekKeys[dayIndex]}`);
};

const formatDateTime = (startDate, endDate) => {
  const start = dayjs(startDate);
  const end = dayjs(endDate);
  const weekDay = getWeekDay(start.day());
  return `${start.format("YYYY.MM.DD")} (${weekDay}) ${start.format("HH:mm")}-${end.format("HH:mm")}`;
};

const isToday = dateString => {
  const today = dayjs().format("YYYY-MM-DD");
  return dateString === today;
};

// 判断日期是否在当前选中的周内
const isInCurrentWeek = dateString => {
  const weekText = t("followUpPlan.calendar.views.week");
  if (calendarView.value !== weekText) return false;
  const currentDate = dayjs(date.value);
  const startOfWeek = currentDate.startOf("week");
  const endOfWeek = currentDate.endOf("week");
  const targetDate = dayjs(dateString);
  return targetDate.isBetween(startOfWeek, endOfWeek, "day", "[]");
};

const resetSearch = () => {
  selectedDoctor.value = "";
  planType.value = "";
  searchUser.value = "";
  fetchTasks();
};

const searchTasks = () => {
  fetchTasks();
};

const navigatePrevious = () => {
  const dayText = t("followUpPlan.calendar.views.day");
  const weekText = t("followUpPlan.calendar.views.week");
  const monthText = t("followUpPlan.calendar.views.month");

  const unit = {
    [dayText]: "day",
    [weekText]: "week",
    [monthText]: "month"
  }[calendarView.value];

  date.value = dayjs(date.value).subtract(1, unit).toDate();
  fetchTasks();
};

const navigateNext = () => {
  const dayText = t("followUpPlan.calendar.views.day");
  const weekText = t("followUpPlan.calendar.views.week");
  const monthText = t("followUpPlan.calendar.views.month");

  const unit = {
    [dayText]: "day",
    [weekText]: "week",
    [monthText]: "month"
  }[calendarView.value];

  date.value = dayjs(date.value).add(1, unit).toDate();
  fetchTasks();
};

const goToday = () => {
  const today = new Date();
  date.value = today;
  fetchTasks(today);
  // 如果今天有任务，自动显示今天的任务
  const todayStr = dayjs(today).format("YYYY-MM-DD");
  const todayTasks = tasks.value.filter(
    task => dayjs(Number(task.startDate)).format("YYYY-MM-DD") === todayStr
  );
  if (todayTasks.length > 0) {
    selectedTasks.value = todayTasks;
  }
};

const createTask = () => {
  currentTask.value = null;
  dialogMode.value = "create";
  dialogVisible.value = true;
};

const editTask = (task, mode) => {
  getFollowUpPlanCondition(task.userId);
  currentTask.value = task;
  dialogMode.value = mode;
  dialogVisible.value = true;
};

const fillRecord = task => {
  router.push({
    path: "/followUpPlan/detail",
    query: {
      planId: task.planId,
      userId: task.userId,
      taskId: task.taskId.toString()
    }
  });
};

const cancelTask = async task => {
  let res = await followApi.cancelTask({
    taskId: task.taskId
  });
  if (res.data.result) {
    ElMessage.success(t("followUpPlan.messages.cancelSuccess"));
    fetchTasks();
  } else {
    ElMessage.error(t("followUpPlan.messages.cancelFailed"));
  }
};

// 处理任务提交
const handleTaskSubmit = formData => {
  console.log("提交的表单数据:", formData);
  // TODO: 根据是否有currentTask.value来判断是创建还是编辑
  // 这里可以调用API进行保存
  dialogVisible.value = false;
  ElMessage.success(
    currentTask.value
      ? t("followUpPlan.messages.editSuccess")
      : t("followUpPlan.messages.createSuccess")
  );
  fetchTasks(); // 刷新任务列表
};
const toolsStore = useToolsStore();

const getFollowUpPlanCondition = async userId => {
  const response = await followApi.getFollowUpPlanCondition({
    userId: userId
  });
  if (response?.data) {
    // 将数据存储到 store 中
    toolsStore.setDictData({
      ...toolsStore.getDictData(),
      followUpPlanCondition: response.data
    });
  }
};
onMounted(() => {
  // 初始化日历视图为月视图
  calendarView.value = t("followUpPlan.calendar.views.month");

  // 初始化时获取今天的数据
  const today = new Date();
  fetchTasks(today);
  // 如果今天有任务，自动显示今天的任务
  const todayStr = dayjs(today).format("YYYY-MM-DD");
  const todayTasks = tasks.value.filter(
    task => dayjs(Number(task.startDate)).format("YYYY-MM-DD") === todayStr
  );
  if (todayTasks.length > 0) {
    selectedTasks.value = todayTasks;
  }

  // 获取医生列表
  followApi.getFollowUpPlanDoctorHealthManager().then(res => {
    console.log(res);
    doctorList.value = res.data.data;
  });
});
// 初始化
</script>

<style scoped lang="scss">
.follow-up-plan {
  padding: 24px;
  background-color: #fff;
  border-radius: 12px;

  .search-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
    justify-content: space-between;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 16px;
    .search-item {
      min-width: 200px;
    }
  }

  :deep(.el-calendar__header) {
    padding: 0;
    margin-bottom: 6px;
  }

  .calendar-header {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    gap: 24px;
    padding-bottom: 6px;
    .calendar-header-left {
      display: flex;
      flex-direction: row;
      gap: 12px;
    }
    .calendar-header-right {
      display: flex;
      flex-direction: row;
      align-items: center;
      gap: 12px;
    }

    .year-month {
      font-size: 20px;
      font-weight: 500;
      min-width: 100px;
    }

    .statistics {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #666;
      flex: 1;

      .divider {
        color: #dcdfe6;
        margin: 0 4px;
      }
    }

    .nav-buttons {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-right: 16px;

      .el-button {
        padding: 8px;
      }
    }

    .el-radio-group {
      margin-left: auto;
    }
  }

  .main-content {
    display: grid;
    grid-template-columns: 1fr 420px;
    gap: 20px;
    margin-bottom: 20px;
    min-height: 600px;

    .calendar-container {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

      .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        // margin-bottom: 8px;

        .calendar-nav {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }

    .task-details {
      max-height: calc(100vh - 200px);

      .empty-state {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .task-list {
        height: 100%;
        overflow-y: auto;
      }

      .task-card {
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 16px;
        border: 1px solid #ebeef5;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);

        .task-time {
          font-size: 16px;
          color: #333;
          margin-bottom: 20px;
        }

        .task-people {
          display: flex;
          flex-direction: row;
          justify-content: space-around;
          gap: 20px;
          margin-bottom: 20px;
          padding-bottom: 20px;
          border-bottom: 1px solid #ebeef5;

          .person-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .avatar-wrapper {
              position: relative;

              .gender-icon {
                position: absolute;
                right: 0px;
                bottom: 6px;
                width: 18px;
                height: 18px;
                background: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

                .el-icon {
                  font-size: 18px;
                }
              }
            }

            .info-text {
              .name {
                font-size: 16px;
                font-weight: 500;
                color: #333;
                margin-bottom: 4px;
              }

              .role {
                font-size: 14px;
                color: #125981;
                padding: 2px 8px;
                background: linear-gradient(300deg, #65c8ff 0%, #61fffb 100%);
                box-shadow: 0px 2px 16px 0px rgba(41, 127, 128, 0.06);
                border-radius: 4px;
                display: inline-block;
              }
            }
          }
        }

        .task-actions {
          display: flex;
          gap: 24px;
          justify-content: space-around;

          .action-link {
            font-size: 14px;
            cursor: pointer;
            text-decoration: none;
            white-space: nowrap;

            &.primary {
              color: #409eff;
              &:hover {
                color: #66b1ff;
              }
            }

            &.danger {
              color: #f56c6c;
              &:hover {
                color: #f78989;
              }
            }
          }
        }
      }
    }
  }

  .create-task-btn {
    margin-left: 10px;
  }
}
</style>
<style lang="scss">
.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;
  position: relative;
  padding: 4px 8px;
  transition: all 0.3s ease;

  &.is-current-week {
    background-color: #ecf5ff;
    border-radius: 4px;
  }

  .date-content {
    display: flex;
    align-items: center;
    gap: 4px;

    .date-number {
      font-size: 16px;
    }

    .today-mark {
      width: 24px;
      height: 24px;
      background-color: #409eff;
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      position: absolute;
      right: 8px;
      top: 8px;
    }
  }

  .task-indicators {
    display: flex;
    flex-direction: column;
    gap: 2px;
    font-size: 12px;

    .task-dot {
      padding: 2px;
      border-radius: 13px;
      color: #fff;

      &.task-type-1 {
        background-color: #409eff;
        width: 100%;
        text-align: left;
      }
      // &.task-type-2 {
      //   background-color: #67c23a;
      // }
      // &.task-type-3 {
      //   background-color: #e6a23c;
      // }
    }
  }
}
.el-calendar-day {
  padding: 0 !important;
}
.is-today {
  background-color: #fff !important;
  border-radius: 4px !important;
  position: relative !important;
  .el-calendar-day span {
    background-color: #409eff !important;
    border-radius: 18px !important;
    color: #fff !important;
    padding: 3px;
    width: 30px;
    text-align: center;
  }
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background-color: #409eff;
    border-radius: 4px 4px 0 0;
  }
}
</style>
